<?php

/**
 * SocialEngine
 *
 * @category   Application_Extensions 
 * @package    Seaocore
 * @copyright  Copyright 2009-2010 BigStep Technologies Pvt. Ltd.
 * @license    http://www.socialengineaddons.com/license/
 * @version    $Id: Core.php 2010-11-18 9:40:21Z SocialEngineAddOns $
 * @author     SocialEngineAddOns
 */
class Seaocore_Api_Core extends Core_Api_Abstract {

  protected $_table;

  /**
   *
   * @param $title: String which are require for truncate
   * @return string
   */
  public function seaddonstruncateTitle($title) {
    $tmpBody = strip_tags($title);
    return ( Engine_String::strlen($tmpBody) > 13 ? Engine_String::substr($tmpBody, 0, 15) . '..' : $tmpBody );
  }

  public function getDefault() {
    Engine_Api::_()->getApi('settings', 'core')->getSettings(Zend_Controller_Front::getInstance());
  }

  // return: CDN enabled or not at the site.
  public function isCdn() {
    $storagemodule = Engine_Api::_()->getDbtable('modules', 'core')->getModule('storage');
    $storageversion = $storagemodule->version;

    $db = Engine_Db_Table::getDefaultAdapter();
    // $type_array = $db->query("SHOW COLUMNS FROM engine4_storage_servicetypes LIKE 'enabled'")->fetch();
    $cdn_path = null;

    if ($storageversion >= '4.1.6') {
      $storageServiceTypeTable = Engine_Api::_()->getDbtable('serviceTypes', 'storage');
      $storageServiceTypeTableName = $storageServiceTypeTable->info('name');

      $storageServiceTable = Engine_Api::_()->getDbtable('services', 'storage');
      $storageServiceTableName = $storageServiceTable->info('name');

      $select = $storageServiceTypeTable->select()
              ->setIntegrityCheck(false)
              ->from($storageServiceTypeTableName, array(null))
              ->join($storageServiceTableName, "$storageServiceTypeTableName.servicetype_id = $storageServiceTableName.servicetype_id", array('enabled', 'config', 'default'))
              ->where("$storageServiceTypeTableName.plugin != ?", "Storage_Service_Local")
              ->where("$storageServiceTypeTableName.enabled = ?", 1);

      $storageCheck = $storageServiceTypeTable->fetchRow($select);
      if (!empty($storageCheck)) {
        if ($storageCheck->enabled == 1 && $storageCheck->default == 1) {
          $cdn_path = true;
        }
      }
    }
    return $cdn_path;
  }

  public function setDefaultConstant() {  
    // Set Emotions Tag
    $file_path = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR
            . 'modules' . DIRECTORY_SEPARATOR
            . "Seaocore/settings/config/emoticons.php";
    $tags = NULL;
    if (file_exists($file_path)) {
      $tags = include $file_path;
    }
    define('SEA_EMOTIONS_TAG', serialize($tags));

    $showLightboxOptionDisplay = Engine_Api::_()->getApi('settings', 'core')->getSetting('seaocore.lightbox.option.display', array());
    $seaocore_display_lightbox = Engine_Api::_()->getApi('settings', 'core')->getSetting('seaocore.display.lightbox', 1);
    define('SEA_DISPLAY_LIGHTBOX', $seaocore_display_lightbox);
    if (!empty($showLightboxOptionDisplay)) {
      define('SEA_SITEPAGEALBUM_LIGHTBOX', in_array('sitepagealbum', $showLightboxOptionDisplay) || $seaocore_display_lightbox);
      define('SEA_SITEBUSINESSALBUM_LIGHTBOX', in_array('sitebusinessalbum', $showLightboxOptionDisplay) || $seaocore_display_lightbox);
      define('SEA_LIST_LIGHTBOX', in_array('list', $showLightboxOptionDisplay) || $seaocore_display_lightbox);
      define('SEA_RECIPE_LIGHTBOX', in_array('recipe', $showLightboxOptionDisplay) || $seaocore_display_lightbox);
      define('SEA_SITEPAGENOTE_LIGHTBOX', in_array('sitepagenote', $showLightboxOptionDisplay) || $seaocore_display_lightbox);
      define('SEA_SITEBUSINESSNOTE_LIGHTBOX', in_array('sitebusinessnote', $showLightboxOptionDisplay) || $seaocore_display_lightbox);
      define('SEA_LIKE_LIGHTBOX', in_array('sitelike', $showLightboxOptionDisplay) || $seaocore_display_lightbox);
      define('SEA_SITEALBUM_LIGHTBOX', in_array('sitealbum', $showLightboxOptionDisplay) || $seaocore_display_lightbox);
    } else {
      define('SEA_SITEPAGEALBUM_LIGHTBOX', $seaocore_display_lightbox);
      define('SEA_SITEBUSINESSALBUM_LIGHTBOX', $seaocore_display_lightbox);
      define('SEA_LIST_LIGHTBOX', $seaocore_display_lightbox);
      define('SEA_RECIPE_LIGHTBOX', $seaocore_display_lightbox);
      define('SEA_SITEPAGENOTE_LIGHTBOX', $seaocore_display_lightbox);
      define('SEA_SITEBUSINESSNOTE_LIGHTBOX', $seaocore_display_lightbox);
      define('SEA_LIKE_LIGHTBOX', $seaocore_display_lightbox);
      define('SEA_SITEALBUM_LIGHTBOX', $seaocore_display_lightbox);
    }

    define('SITEALBUM_ENABLED', Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('sitealbum'));
    define('SITEACTIVITY_ENABLED', Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('advancedactivity'));

    if ($seaocore_display_lightbox) {
      if ((SITEALBUM_ENABLED || SITEACTIVITY_ENABLED)) {
        define('SEA_ACTIVITYFEED_LIGHTBOX', $seaocore_display_lightbox);
      } else {
        define('SEA_ACTIVITYFEED_LIGHTBOX', 0);
      }
    } else {
      if ((SITEALBUM_ENABLED || SITEACTIVITY_ENABLED)) {
        if (!empty($showLightboxOptionDisplay)) {
          define('SEA_ACTIVITYFEED_LIGHTBOX', in_array('activity', $showLightboxOptionDisplay));
        } else {
          define('SEA_ACTIVITYFEED_LIGHTBOX', 0);
        }
      } else {
        define('SEA_ACTIVITYFEED_LIGHTBOX', 0);
      }
    }

		if (SITEALBUM_ENABLED) {
      if (!empty($showLightboxOptionDisplay)) {
        define("SEA_GROUP_LIGHTBOX", in_array("group", $showLightboxOptionDisplay));
        define("SEA_EVENT_LIGHTBOX", in_array("event", $showLightboxOptionDisplay));
        define("SEA_YNEVENT_LIGHTBOX", in_array("ynevent", $showLightboxOptionDisplay));
        define("SEA_ADVGROUP_LIGHTBOX", in_array("advgroup", $showLightboxOptionDisplay));
      } else {
        define("SEA_GROUP_LIGHTBOX", 0);
        define("SEA_EVENT_LIGHTBOX", 0);
        define("SEA_YNEVENT_LIGHTBOX", 0);
        define("SEA_ADVGROUP_LIGHTBOX", 0);
      }
    }

    $enableSubModules = array();
    $includeModules = array("sitepagealbum" => "Directory / Pages - Photo Albums Extension", "sitepagenote" => "Directory / Pages - Notes Extension", "list" => "Listing", "recipe" => "Recipe", "sitelike" => "Likes Plugin and Widgets", "sitealbum" => "Advanced Photo Albums","sitebusinessalbum" => "Directory / Businesses - Photo Albums Extension", "sitebusinessnote" => "Directory / Businesses - Notes Extension");

    $enableAllModules = Engine_Api::_()->getDbtable('modules', 'core')->getEnabledModuleNames();
    $enableModules = array_intersect(array_keys($includeModules), $enableAllModules);
    if (!empty($enableModules)) {
      define('SEA_PHOTOLIGHTBOX_DOWNLOAD', Engine_Api::_()->getApi('settings', 'core')->getSetting('seaocore.photo.download', 1));
      define('SEA_PHOTOLIGHTBOX_REPORT', Engine_Api::_()->getApi('settings', 'core')->getSetting('seaocore.photo.report', 1));
      define('SEA_PHOTOLIGHTBOX_MAKEPROFILEPHOTO', Engine_Api::_()->getApi('settings', 'core')->getSetting('seaocore.photo.makeprofile', 1));
      define('SEA_PHOTOLIGHTBOX_SHARE', Engine_Api::_()->getApi('settings', 'core')->getSetting('seaocore.photo.share', 1));
    } else {
      define('SEA_PHOTOLIGHTBOX_DOWNLOAD', 0);
      define('SEA_PHOTOLIGHTBOX_REPORT', 0);
      define('SEA_PHOTOLIGHTBOX_MAKEPROFILEPHOTO', 0);
      define('SEA_PHOTOLIGHTBOX_SHARE', 0);
    }
  }

  //GETTING THE FACEBOOK INSTANCE FOR FETCHING THE USER'S ALLWED FACEBOOK INFO.
  public function getFBInstance() {

    // Need to initialize
    $settings = Engine_Api::_()->getApi('settings', 'core')->getSetting('core.facebook');
    if (empty($settings['secret']) ||
            empty($settings['appid'])
    ) {
      $this->_api = null;
      Zend_Registry::set('Seaocore_Api_Facebook_Api', $this->_api);
      return false;
    }

    $this->_api = new Seaocore_Api_Facebook_Api(array(
                'appId' => $settings['appid'],
                'secret' => $settings['secret'],
                'cookie' => false, // @todo make sure this works
                'baseDomain' => $_SERVER['HTTP_HOST'],
            ));
    Zend_Registry::set('Seaocore_Api_Facebook_Api', $this->_api);

    // Try to log viewer in?
    $viewer = Engine_Api::_()->user()->getViewer();
//    $facebooksepageModule = Engine_Api::_()->getDbtable('modules', 'core')->getModule('facebooksepage');
//    if (!empty($facebooksepageModule)) {
//      if (!isset($_SESSION['facebook_uid']) ||
//              @$_SESSION['facebook_lock'] !== $viewer->getIdentity()) {
//        $_SESSION['facebook_lock'] = $viewer->getIdentity();
//        if ($this->_api->getUser()) {
//          $_SESSION['facebook_uid'] = $this->_api->getUser();
//          $this->_api->setPersistentData('code', '');
//          $this->_api->setPersistentData('access_token', '');
//        }
//        //else if( $viewer && $viewer->getIdentity() ) {
//        //        $FacebookUserTable = Engine_Api::_()->getDbtable('facebook', 'user');
//        //        $FacebookUserTableName = Engine_Api::_()->getDbtable('facebook', 'user')->info('name');
//        //        // Try to get from db
//        //        $info = $FacebookUserTable->select()
//        //            ->from($FacebookUserTableName)
//        //            ->where('user_id = ?', $viewer->getIdentity())
//        //            ->query()
//        //            ->fetch(); 
//        //        if( is_array($info) && !empty($info['facebook_uid']) &&
//        //            !empty($info['access_token']) && !empty($info['code']) ) {
//        //          $_SESSION['facebook_uid'] = $info['facebook_uid'];
//        //          $this->_api->setPersistentData('code', $info['code']);
//        //          $this->_api->setPersistentData('access_token', $info['access_token']);
//        //        } else {
//        //          // Could not get
//        //          $_SESSION['facebook_uid'] = false;
//        //        }
//        //      }
//        else {
//          // Could not get
//          $_SESSION['facebook_uid'] = false;
//          $this->_api->setPersistentData('code', '');
//          $this->_api->setPersistentData('access_token', '');
//        }
//      }
//    } else {
    if (!isset($_SESSION['facebook_uid']) ||
            @$_SESSION['facebook_lock'] !== $viewer->getIdentity()) {
      $_SESSION['facebook_lock'] = $viewer->getIdentity();
      if ($this->_api->getUser()) {
        $_SESSION['facebook_uid'] = $this->_api->getUser();
      } else if ($viewer && $viewer->getIdentity()) {
        $FacebookUserTable = Engine_Api::_()->getDbtable('facebook', 'user');
        $FacebookUserTableName = Engine_Api::_()->getDbtable('facebook', 'user')->info('name');
        // Try to get from db
        $info = $FacebookUserTable->select()
                ->from($FacebookUserTableName)
                ->where('user_id = ?', $viewer->getIdentity())
                ->query()
                ->fetch();
        if (is_array($info) && !empty($info['facebook_uid']) &&
                !empty($info['access_token']) && !empty($info['code'])) {
          $_SESSION['facebook_uid'] = $info['facebook_uid'];
          $this->_api->setPersistentData('code', $info['code']);
          $this->_api->setPersistentData('access_token', $info['access_token']);
        } else {
          // Could not get
          $_SESSION['facebook_uid'] = false;
        }
      } else {
        // Could not get
        //$_SESSION['facebook_uid'] = false;
      }
    }
    //}


    return $this->_api;
  }

  /**
   * Returns array of "Mutual Friend" between "$friend_id" and "viewer_id".
   *
   * @param $friend_id: Find out mutual friend between "Pass friend id" and "Loggden user id".
   * @return Array.
   */
  public function getMutualFriend($friend_id, $LIMIT = null) {

    $mutualFriendArray = array();

    //GET THE VIEWER ID.
    $viewer_id = Engine_Api::_()->user()->getViewer()->getIdentity();

    $memberTable = Engine_Api::_()->getDbtable('membership', 'user');
    $memberTableName = $memberTable->info('name');

    $select = $memberTable->select()
            ->setIntegrityCheck(false)
            ->from($memberTableName, array('user_id'))
            ->join($memberTableName, "`{$memberTableName}`.`user_id`=`{$memberTableName}_2`.user_id", null)
            ->where("`{$memberTableName}`.resource_id = ?", $friend_id) // FRIEND ID.
            ->where("`{$memberTableName}_2`.resource_id = ?", $viewer_id) // VIEWER ID.
            ->where("`{$memberTableName}`.active = ?", 1)
            ->where("`{$memberTableName}_2`.active = ?", 1);
    if (!empty($LIMIT)) {
      $select->limit($LIMIT);
    }
    return Zend_Paginator::factory($select);
//     if (!empty($fetch_mutual_friend)) {
//       foreach ($fetch_mutual_friend as $mutual_friend_id) {
//         $mutualFriendArray[] = $mutual_friend_id['user_id'];
//       }
//     }
  }

  public function getCategory($resource_type, $resource) {

    //Start Work for faq plugin.
    if ($resource_type == 'sitefaq_faq' && !empty($resource['category_id'])) {
    	$first_category_id_array = explode( '["', $resource['category_id']);
			$first_category_id_array = explode( '"', $first_category_id_array[1]);
			$resource['category_id'] = $first_category_id_array[0];
    }
    //End Work for faq plugin.

    if (empty($resource['category_id'])) {
			return;
		}

    switch ($resource_type) {
      case 'event':
        if (!Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('event')) {
				  $Table = Engine_Api::_()->getItemTable('ynevent_category');
				} else {
					$Table = Engine_Api::_()->getDbtable('categories', $resource_type);
				}
        $title = 'title';
      break;
      case 'group':
      	if (!Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('group')) {
				  $Table = Engine_Api::_()->getDbtable('categories', 'advgroup');
				} else {
					$Table = Engine_Api::_()->getDbtable('categories', $resource_type);
				}
        $title = 'title';
        break;
      case 'forum':
        if (!Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('forum')) {
				  $Table = Engine_Api::_()->getItemTable('ynforum_category');
				} else {
					$Table = Engine_Api::_()->getDbtable('categories', $resource_type);
				}
        $title = 'title';
        break;
      case 'recipe':
      case 'document':
      case 'video':
        if (!Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('video')) {
				  $Table = Engine_Api::_()->getItemTable('video_category');
				} else {
					$Table = Engine_Api::_()->getDbtable('categories', $resource_type);
				}
        $title = 'category_name';
        break;
      case 'classified':
        $Table = Engine_Api::_()->getDbtable('categories', $resource_type);
        $title = 'category_name';
        break;
      case 'album':
      case 'blog':
        $Table = Engine_Api::_()->getItemTable($resource_type. '_category');
        $title = 'category_name';
        break;
      case 'list_listing':
        $Table = Engine_Api::_()->getDbtable('categories', 'list');
        $title = 'category_name';
        break;
      case 'sitepage_page':
        $Table = Engine_Api::_()->getDbtable('categories', 'sitepage');
        $title = 'category_name';
        break;
      case 'sitebusiness_business':
        $Table = Engine_Api::_()->getDbtable('categories', 'sitebusiness');
        $title = 'category_name';
        break;
      case 'sitefaq_faq':
        $Table = Engine_Api::_()->getDbtable('categories', 'sitefaq');
        $title = 'category_name';
        break;
      default:
        return;  
    }
    return $Table->select()->from($Table, new Zend_Db_Expr($title))
                    ->where('category_id = ?', $resource['category_id'])->limit(1)->query()->fetchColumn();
  }

  /**
   * Returns true / false if "Friend Id" is the friend of "Loggden User"
   *
   * @param $friend_id: Friend Id,
   * @return true or false
   */
  public function isMember($friend_id) {

    //GET THE VIEWER ID.
    $viewer_id = Engine_Api::_()->user()->getViewer()->getIdentity();
    $isFriend = false;

    //FETCH FRIEND ID FROM DATABASE.
    $memberTable = Engine_Api::_()->getDbtable('membership', 'user');
    $memberTableName = $memberTable->info('name');

    $select = $memberTable->select()
            ->where($memberTableName . '.active = ?', 1)
            ->where($memberTableName . '.resource_id = ?', $friend_id)
            ->where($memberTableName . '.user_id = ?', $viewer_id);

    $fetch = $select->query()->fetchAll();
    if (!empty($fetch)) {
      $isFriend = true;
    }
    return $isFriend;
  }

  public function canSendUserMessage($subject) {
    // Not logged in
    $viewer = Engine_Api::_()->user()->getViewer();
    if (!$viewer->getIdentity() || $viewer->getGuid(false) === $subject->getGuid(false)) {
      return false;
    }
    // Get setting?
    $permission = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'messages', 'create');
    if (Authorization_Api_Core::LEVEL_DISALLOW === $permission) {
      return false;
    }
    $messageAuth = Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'messages', 'auth');
    if ($messageAuth == 'none') {
      return false;
    } else if ($messageAuth == 'friends') {
      // Get data
      $direction = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('user.friends.direction', 1);
      if (!$direction) {
        //one way
        $friendship_status = $viewer->membership()->getRow($subject);
      }
      else
        $friendship_status = $subject->membership()->getRow($viewer);

      if (!$friendship_status || $friendship_status->active == 0) {
        return false;
      }
    }
    return true;
  }

  public function baseOnContentOwner(User_Model_User $viewer, Core_Model_Item_Abstract $item) {

    $settingsCoreApi = Engine_Api::_()->getApi('settings', 'core');
    if ($item->getType() == 'sitepage_page') {
      $advancedactivityEnable = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('advancedactivity');
      if ($advancedactivityEnable && $settingsCoreApi->sitepage_feed_type && $item->isOwner($viewer)) {
        return true;
      }
    } elseif ($item->getType() == 'sitebusiness_business') {
      $advancedactivityEnable = Engine_Api::_()->getDbtable('modules', 'core')->isModuleEnabled('advancedactivity');
      if ($advancedactivityEnable && $settingsCoreApi->sitebusiness_feed_type && $item->isOwner($viewer)) {
        return true;
      }
    }
    return false;
  }

  public function isLessThan420ActivityModule() {
    $activityModule = Engine_Api::_()->getDbtable('modules', 'core')->getModule('activity');
    $activityModuleVersion = $activityModule->version;
    if ($activityModuleVersion < '4.1.8') {
      return true;
    } else {
      return false;
    }
  }
  
  /**
   * Added Widget On Page
   *
   * @return bool
   */
  public function hasAddedWidgetOnPage($pageName, $widgetName, $params =array()) {
    $isCoreActivtyFeedWidget = false;

    $pagesTable = Engine_Api::_()->getDbtable('pages', 'core');
    $pagesTableName = $pagesTable->info('name');
    $contentsTable = Engine_Api::_()->getDbtable('content', 'core');
    $contentsTableName = $contentsTable->info('name');

    $select = $contentsTable->select()
            ->setIntegrityCheck(false)
            ->from($contentsTableName, array($contentsTableName . '.name'))
            ->join($pagesTableName, "`{$pagesTableName}`.page_id = `{$contentsTableName}`.page_id  ", null)
            ->where($pagesTableName . '.name = ?', $pageName)
            ->where($contentsTableName . '.name = ?', $widgetName);
    $row = $contentsTable->fetchRow($select);
    if (!empty($row))
      $isCoreActivtyFeedWidget = true;
    return $isCoreActivtyFeedWidget;
  }
}

?>